package com.school.information.core.security.provider;

import cn.hutool.core.util.ObjectUtil;
import com.school.information.core.security.authen.WechatAppAuthenticationToken;
import com.school.information.core.security.entity.WechatAppUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 微信小程序登录验证， 模仿 DaoAuthenticationProvider
 */
public class WechatAppUserAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public WechatAppUserAuthenticationProvider() {

    }

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 自定义小程序认证登录 根据小程序openid获取小程序用户信息
        WechatAppUser wechatAppUser = (WechatAppUser) userDetailsService.loadUserByUsername(authentication.getName());
        if (ObjectUtil.isEmpty(wechatAppUser)) {
            throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
        }
        // 注意要调用 authenticated() 方法 这个是认证通过了的
        WechatAppAuthenticationToken result = WechatAppAuthenticationToken.authenticated(wechatAppUser, authentication.getCredentials(), null);
        result.setDetails(authentication.getDetails());

        return result;
    }

    public boolean supports(Class<?> authentication) {
        return WechatAppAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }
}